<?php
/**
 * 买单付款
 */
namespace app\smartbc\controller\api\v1;
use app\smartbc\controller\api\Base;
use app\smartbc\model\SmartbcOrder;
use app\smartbc\model\SmartbcStore;
use app\smartbc\model\SmartbcCoupon;
use app\smartbc\model\SmartbcCouponUser;
use app\smartbc\model\SmartbcConfig;
use app\common\facade\WechatPay;

class Storepay extends Base{

    protected $config;

    /**
     * 初始化当前应用管理员是不是联盟城市账户
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
        $this->config = SmartbcConfig::getConfig($this->member_miniapp_id);
    }

    /**
    * 读取买单商家信息和优惠券
    * @return void
    */
    public function index(){
        $param['store_id']  = $this->request->param('store_id/d');
        $param['chain_id']  = $this->request->param('chain_id/d');
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        if(empty($param['store_id'])){
            return enjson(404,'为找到付款好店');
        }
        $store = SmartbcStore::where(['is_lock' => 0,'id' => $param['store_id']])->field('id,name')->find();
        if(empty($store)){
            return enjson(303,'未找到付款好店',['url' =>'/pages/index']);
        }
        if(!empty($param['chain_id'])){
            $store = $store->chain()->where('id',$param['chain_id'])->field('id,title,store_id')->find();
            if(empty($store)){
                return enjson(303,'未找到付款分店',['url' =>'/pages/index']);
            }
            $store->name     = $store->title;
            $store->chain_id = $store->id;
            $store->id       = $store->store_id;
        }
        $is_get_coupon = 0;
        if(empty($this->config->is_pay_open_coupon)){
            $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
            $condition[] = ['uid','=',$this->user->id];
            $condition[] = ['is_end','=',0];
            $condition[] = ['money','=',0];
            $condition[] = ['store_id','=',$param['store_id']];
            $coupon = SmartbcCouponUser::where($condition)->field('id,name,tips,howmuch,store_id,price,types,coupon_id,discount,create_time')->order('create_time desc')->select();
            foreach ($coupon as $key => $value){
                $coupon[$key]->is_get_coupon = 0;
                $coupon[$key]->end_time      = $this->config->end_time * 60 * 60;
            }
        }else{
            $coupon = SmartbcCoupon::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $param['store_id'],'is_lock' => 0,'is_end' => 0])->order('is_top desc,sort desc,create_time desc')->select();
            foreach ($coupon as $key => $info){
                $coupon[$key]->end_time      = $info->create_time + $this->config->end_time * 60 * 60;
                $coupon[$key]->is_get_coupon = 0; 
            }
            $is_get_coupon = 1;
        }
        return enjson(200,['coupon' => $coupon ,'store' => $store,'is_get_coupon' => $is_get_coupon]);
    }
    
    /**
     * 微信给商家支付
     * @param string $no
     * @return void
     */
    public function wechat(){
        if (request()->isPost()) {
            $rule = [
                'member_miniapp_id' => $this->miniapp_id,
                'store_id'          => $this->request->param('store_id/d'),
                'chain_id'          => $this->request->param('chain_id/d',0),
                'user_couponr_id'   => $this->request->param('user_couponr_id/d',0),
                'money'             => $this->request->param('money/f'),
                'amount'            => $this->request->param('amount/f'),
                'uid'               => $this->user->id,
            ];
            $validate = $this->validate($rule,'Dopay.gopay');
            if (true !== $validate) {
                return enjson(204,$validate);
            }
            //判断好店
            $store = SmartbcStore::where(['member_miniapp_id' => $this->miniapp_id,'id' => $rule['store_id'],'is_lock' => 0])->find();
            if(empty($store)){
                return enjson(204,'未找到商户');
            }
            $store->chain_id = 0;
            if(!empty($rule['chain_id'])){
                $chain = $store->chain()->where('id',$rule['chain_id'])->field('id,title,store_id')->find();
                if(empty($chain)){
                    return enjson(204,'未找到付款分店');
                }
                $store->title = $chain->title;
                $store->chain_id = $chain->id;
            }
            if(empty($store->manage_uid)){
                return enjson(204,'未设置老板');
            }
            if(empty($store->mch_id)){
                return enjson(204,'未找到商家微信商户号');
            }
            //计算付款金额
            $amount = SmartbcOrder::countPrice($rule);
            if(!$amount){
                return enjson(204,'优惠券不满足使用条件');
            }
            //创建订单
            $order_no = $this->user->invite_code.order_no();
            //唤醒微信支付参数
            $payparm = [
                'openid'     => $this->user->miniapp_uid,
                'miniapp_id' => $this->miniapp_id,
                'name'       => $store->name,
                'order_no'   => $order_no,
                'total_fee'  => $amount['price'] * 100,
                'notify_url' => api(1,'smartbc/notify/storepay',$this->miniapp_id),
            ];
            $payparm['mchid'] = $store->mch_id;
            if(!empty($amount['coupon'])){
                if($amount['coupon']->parent_store_id > 0){
                    $rule['parent_store_id']   = $amount['coupon']->parent_store_id;  //引荐的店铺
                    $payparm['profit_sharing'] = 'Y';
                }
                $rule['coupon_cache'] = $amount['coupon'];    //优惠券
            }
            $ispay = WechatPay::orderPay($payparm);
            if($ispay['code'] == 0){
                return enjson(204,$ispay['msg']);
            }
            //添加订单记录
            $rule['order_no']       = $order_no;
            $rule['price']          = $amount['price'];    //实际金额
            $rule['store_chain_id'] = $store->chain_id;    //分店ID
            $rel = SmartbcOrder::addOrder($rule);
            if(!$rel){
                return enjson(204,'订单创建失败');
            }
            return enjson(200,'成功',$ispay['data']);
        }
    }

}